<script>
import { defineComponent, onUnmounted, reactive, toRaw, watch } from 'vue'
import { tagList } from '@Config/server/api'
import FastCheckBox from '@Components/fastCheckBox'
import * as Antd from 'ant-design-vue'
import { findIndex } from 'lodash'
export default defineComponent({
  emits: ['result'],
  props: {
    marks: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  setup(props, context) {
    let tags = reactive({
      data: [],
    })

    let checked = reactive({})
    let checked_origin = reactive({})
    tagList({ size: 10000, index: 1 }).then((x) => {
      // checked_origin.data = []
      tags.data =
        x.data?.records.map((x) => {
          checked[x.name + x.id] = []
          checked_origin[x.name + x.id] = []
          x.child.map((xx) => {
            if (findIndex(props.marks, { tagId: xx.id }) >= 0) {
              checked[x.name + x.id].push(xx.id)
              checked_origin[x.name + x.id].push({ ...xx })

              //   checked_origin.data.push({ ...xx })
            }
            xx.label = xx.name
            xx.value = xx.id
          })
          return x
        }) || []

      //默认更新一下
      let _r = []

      for (var prop in checked) {
        _r = [..._r, ...checked[prop]]
      }
      context.emit('result', {
        list: _r,
        origin: toRaw(checked_origin),
      })
    })

    let resultHandler = (x, params) => {
      checked[x.name + x.id] = params.list
      checked_origin[x.name + x.id] = params.origin
      let _r = []
      for (var prop in checked) {
        _r = [..._r, ...checked[prop]]
      }
      context.emit('result', { list: _r, origin: toRaw(checked_origin) })
    }

    let _w = watch(
      () => props.marks,
      () => {
        for (var prop in checked) {
          checked[prop] = []
        }
        tags.data.map((x) => {
          x.child.map((xx) => {
            if (findIndex(props.marks, { tagId: xx.id }) >= 0) {
              checked[x.name + x.id].push(xx.id)
              checked_origin[x.name + x.id].push(xx)
            }
          })
        })
      },
      {
        deep: true,
      }
    )

    onUnmounted(() => {
      _w()
    })
    return {
      tags,
      checked,
      resultHandler,
      props,
    }
  },
  render() {
    return (
      <Antd.Row gutter={[20, 20]}>
        {this.tags.data.map((x) => {
          return (
            <Antd.Col span={24}>
              <>
                <b>{x.name}</b>
                <FastCheckBox
                  list={x.child}
                  checked_list={[...this.checked[x.name + x.id]]}
                  onResult={({ params }) => {
                    this.resultHandler(x, params)
                  }}
                />
                <div class="divider" />
              </>
            </Antd.Col>
          )
        })}
      </Antd.Row>
    )
  },
})
</script>
